import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueDevTools from 'vite-plugin-vue-devtools'
import { viteStaticCopy } from 'vite-plugin-static-copy'
import fs from 'fs'
import path from 'path'

const cdn = 'https://image-cdn.com'

// 构建后批量替换 dist 目录下所有文件中的图片路径为 CDN 路径
function cdnImageReplaceAllPlugin() {
  return {
    name: 'replace-cdn-image-path-all',
    apply: 'build',
    closeBundle() {
      const distDir = path.resolve(__dirname, 'dist')
      const exts = ['.html', '.js', '.css']
      function replaceInFile(filePath) {
        let content = fs.readFileSync(filePath, 'utf-8')
        content = content.replace(
          /(["'(=])\/assets\/(.*?\.(png|jpe?g|gif|svg|webp|avif)(\?[^"')\s]*)?)/gi,
          (match, prefix, path) => `${prefix}${cdn}/assets/${path}`
        )
        fs.writeFileSync(filePath, content, 'utf-8')
      }
      function walk(dir) {
        fs.readdirSync(dir).forEach(file => {
          const fullPath = path.join(dir, file)
          if (fs.statSync(fullPath).isDirectory()) {
            walk(fullPath)
          } else if (exts.includes(path.extname(fullPath))) {
            replaceInFile(fullPath)
          }
        })
      }
      walk(distDir)
    }
  }
}

function atAliasAssetsReplacePlugin() {
  return {
    name: 'replace-at-alias-assets',
    apply: 'build',
    closeBundle() {
      const fs = require('fs')
      const path = require('path')
      const distDir = path.resolve(__dirname, 'dist')
      const exts = ['.html', '.js', '.css']
      function replaceInFile(filePath) {
        let content = fs.readFileSync(filePath, 'utf-8')
        // 替换 @/assets 为 /assets
        content = content.replace(/(['"`(=])@\/assets\//g, '$1/assets/')
        fs.writeFileSync(filePath, content, 'utf-8')
      }
      function walk(dir) {
        fs.readdirSync(dir).forEach(file => {
          const fullPath = path.join(dir, file)
          if (fs.statSync(fullPath).isDirectory()) {
            walk(fullPath)
          } else if (exts.includes(path.extname(fullPath))) {
            replaceInFile(fullPath)
          }
        })
      }
      walk(distDir)
    }
  }
}

export default defineConfig({
  plugins: [
    vue(),
    vueDevTools(),
    viteStaticCopy({
      targets: [
        {
          src: 'src/assets/**/*',
          dest: 'assets'
        }
      ]
    }),
    cdnImageReplaceAllPlugin(),
    atAliasAssetsReplacePlugin()
  ],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    },
  },
  build: {
    assetsInlineLimit: 0,
    rollupOptions: {
      output: {
        assetFileNames: (assetInfo) => {
          // 只处理图片资源
          const originalNames = assetInfo.originalFileNames;
          if (Array.isArray(originalNames) && originalNames.length > 0) {
            const relPath = originalNames[0].replace(/\\/g, '/');
            const match = relPath.match(/src\/assets\/(.+)/);
            if (match) {
              return `assets/${match[1]}`;
            }
          }
          return 'assets/[name][extname]';
        }
      }
    }
  },
  // experimental: {
  //   renderBuiltUrl(filename, { type, hostId, hostType }) {
  //     if (
  //       filename.endsWith('.webm') ||
  //       filename.endsWith('.png') ||
  //       filename.endsWith('.jpg') ||
  //       filename.endsWith('.gif') ||
  //       filename.endsWith('.jpeg') ||
  //       filename.endsWith('.svg')
  //     ) {
  //       console.log(filename,type, hostId, hostType)
  //       const name = filename.replace('assets/images/', '');
  //       return `https://cdnURL/images/${name}`;
  //     }

  //     return { relative: true};
  //   },
  // },
})


